﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using ThaireInvestmentWeb.ExcelWSService;
using ThaireInvestmentWeb.Models.criteria;
using ThaireInvestmentWeb.Models.grid;
using ThaireInvestmentWeb.ReportServiceRef;

namespace ThaireInvestmentWeb.Controllers
{
    public class HomeController : Controller
    {
        const int pageSize = 20;
        //
        // GET: /Transaction/

        public ActionResult Index()
        {
            //ViewBag.Message = "รายงาน";
            ObservableCollection<ReportSearchResult> gridList = new ObservableCollection<ReportSearchResult>();
            return View(gridList);
        }

        public ActionResult Search(int? page=1)
        {
            string mode = Request["btnSearch"];
            if (mode == null)
            {
                mode = "Export";
            }
            else
            {
                mode = "Search";
            }
            Console.WriteLine(Request["btnSearch"]);
            Console.WriteLine(Request["btnExport"]);

            string company = Request["SelectCompany"];

            string financialInstrument = Request["selectFinancialInstrument"];
            string assetClass = Request["selectAssetClass"];
            string symbol = Request["txtSymbol"];
            string issuer = Request["SelectIssuer"];
            string keepAt = Request["selectKeepAt"];
            string timeToMaturityYearFrom = Request["selectTimeToMaturityYearFrom"];
            string timeToMaturityMonthFrom = Request["selectTimeToMaturityMonthFrom"];
            string timeToMaturityYearTo = Request["selectTimeToMaturityYearTo"];
            string timeToMaturityMonthTo = Request["selectTimeToMaturityMonthTo"];
            string afterMaturedYearFrom = Request["selectAfterMaturedYearFrom"];
            string afterMaturedMonthFrom = Request["selectAfterMaturedMonthFrom"];
            string selectAfterMaturedYearTo = Request["selectAfterMaturedYearTo"];
            string selectAfterMaturedMonthTo = Request["selectAfterMaturedMonthTo"];
            string tranDateFrom = Request["dtTranDateFrom"];
            string tranDateTo = Request["dtTranDateTo"];
            string atatus = Request["selectStatus"];
            string maxMin = Request["chkMaxMin"];
            string related = Request["selectRelated"];

            if (page == 1)
            {
                if (company == null)
                {
                    mode = "Search";
                    ViewBag.company = Session["company"];
                    ViewBag.financialInstrument = Session["financialInstrument"];
                    ViewBag.assetClass = Session["assetClass"];
                    ViewBag.symbol = Session["symbol"];
                    ViewBag.issuer = Session["issuer"];
                    ViewBag.keepAt = Session["keepAt"];
                    ViewBag.timeToMaturityYearFrom = Session["timeToMaturityYearFrom"];
                    ViewBag.timeToMaturityMonthFrom = Session["timeToMaturityMonthFrom"];
                    ViewBag.timeToMaturityYearTo = Session["timeToMaturityYearTo"];
                    ViewBag.timeToMaturityMonthTo = Session["timeToMaturityMonthTo"];
                    ViewBag.afterMaturedYearFrom = Session["afterMaturedYearFrom"];
                    ViewBag.afterMaturedMonthFrom = Session["afterMaturedMonthFrom"];
                    ViewBag.selectAfterMaturedYearTo = Session["selectAfterMaturedYearTo"];
                    ViewBag.selectAfterMaturedMonthTo = Session["selectAfterMaturedMonthTo"];
                    ViewBag.tranDateFrom = Session["tranDateFrom"];
                    ViewBag.tranDateTo = Session["tranDateTo"];
                    ViewBag.atatus = Session["atatus"];
                    ViewBag.max = Session["max"];
                    ViewBag.min = Session["min"];
                    ViewBag.related = Session["related"];
                }
                else
                {
                    ViewBag.company = company;
                    ViewBag.financialInstrument = financialInstrument;
                    ViewBag.assetClass = assetClass;
                    ViewBag.symbol = symbol;
                    ViewBag.issuer = issuer;
                    ViewBag.keepAt = keepAt;
                    ViewBag.timeToMaturityYearFrom = timeToMaturityYearFrom;
                    ViewBag.timeToMaturityMonthFrom = timeToMaturityMonthFrom;
                    ViewBag.timeToMaturityYearTo = timeToMaturityYearTo;
                    ViewBag.timeToMaturityMonthTo = timeToMaturityMonthTo;
                    ViewBag.afterMaturedYearFrom = afterMaturedYearFrom;
                    ViewBag.afterMaturedMonthFrom = afterMaturedMonthFrom;
                    ViewBag.selectAfterMaturedYearTo = selectAfterMaturedYearTo;
                    ViewBag.selectAfterMaturedMonthTo = selectAfterMaturedMonthTo;
                    ViewBag.tranDateFrom = tranDateFrom;
                    ViewBag.tranDateTo = tranDateTo;
                    ViewBag.atatus = atatus;                    
                    ViewBag.related = related;
                    if (maxMin == "max")
                    {

                        ViewBag.max = "on";
                        ViewBag.min = "";
                    }
                    else if (maxMin == "min")
                    {
                        ViewBag.max = "";
                        ViewBag.min = "on";
                    }
                    else
                    {
                        ViewBag.max = "";
                        ViewBag.min = "";
                    }
                }

                Session["company"] = ViewBag.company;
                Session["financialInstrument"] = ViewBag.financialInstrument;
                Session["assetClass"] = ViewBag.assetClass;
                Session["symbol"] = ViewBag.symbol;
                Session["issuer"] = ViewBag.issuer;
                Session["keepAt"] = ViewBag.keepAt;
                Session["timeToMaturityYearFrom"] = ViewBag.timeToMaturityYearFrom;
                Session["timeToMaturityMonthFrom"] = ViewBag.timeToMaturityMonthFrom;
                Session["timeToMaturityYearTo"] = ViewBag.timeToMaturityYearTo;
                Session["timeToMaturityMonthTo"] = ViewBag.timeToMaturityMonthTo;
                Session["afterMaturedYearFrom"] = ViewBag.afterMaturedYearFrom;
                Session["afterMaturedMonthFrom"] = ViewBag.afterMaturedMonthFrom;
                Session["selectAfterMaturedYearTo"] = ViewBag.selectAfterMaturedYearTo;
                Session["selectAfterMaturedMonthTo"] = ViewBag.selectAfterMaturedMonthTo;
                Session["tranDateFrom"] = ViewBag.tranDateFrom;
                Session["tranDateTo"] = ViewBag.tranDateTo;
                Session["atatus"] = ViewBag.atatus;
                Session["max"] = ViewBag.max;
                Session["min"] = ViewBag.min;
                Session["related"] = ViewBag.related;

            }
            else
            {
                mode = "Search";

                ViewBag.company = Session["company"];
                ViewBag.financialInstrument = Session["financialInstrument"];
                ViewBag.assetClass = Session["assetClass"];
                ViewBag.symbol = Session["symbol"];
                ViewBag.issuer = Session["issuer"];
                ViewBag.keepAt = Session["keepAt"];
                ViewBag.timeToMaturityYearFrom = Session["timeToMaturityYearFrom"];
                ViewBag.timeToMaturityMonthFrom = Session["timeToMaturityMonthFrom"];
                ViewBag.timeToMaturityYearTo = Session["timeToMaturityYearTo"];
                ViewBag.timeToMaturityMonthTo = Session["timeToMaturityMonthTo"];
                ViewBag.afterMaturedYearFrom = Session["afterMaturedYearFrom"];
                ViewBag.afterMaturedMonthFrom = Session["afterMaturedMonthFrom"];
                ViewBag.selectAfterMaturedYearTo = Session["selectAfterMaturedYearTo"];
                ViewBag.selectAfterMaturedMonthTo = Session["selectAfterMaturedMonthTo"];
                ViewBag.tranDateFrom = Session["tranDateFrom"];
                ViewBag.tranDateTo = Session["tranDateTo"];
                ViewBag.atatus = Session["atatus"];
                ViewBag.max = Session["max"];
                ViewBag.min = Session["min"];
                ViewBag.related = Session["related"];
            }


            ReportCriteria crit = new ReportCriteria()
            {
                company = ViewBag.company,

                financialInstrument = ViewBag.financialInstrument,
                assetClass = ViewBag.assetClass,
                symbol = ViewBag.symbol,
                issuer = ViewBag.issuer,
                keepAt = ViewBag.keepAt,
                timeToMaturityYearFrom = ViewBag.timeToMaturityYearFrom,
                timeToMaturityMonthFrom = ViewBag.timeToMaturityMonthFrom,
                timeToMaturityYearTo = ViewBag.timeToMaturityYearTo,
                timeToMaturityMonthTo = ViewBag.timeToMaturityMonthTo,
                afterMaturedYearFrom = ViewBag.afterMaturedYearFrom,
                afterMaturedMonthFrom = ViewBag.afterMaturedMonthFrom,
                selectAfterMaturedYearTo = ViewBag.selectAfterMaturedYearTo,
                selectAfterMaturedMonthTo = ViewBag.selectAfterMaturedMonthTo,
                tranDateFrom = ViewBag.tranDateFrom,
                tranDateTo = ViewBag.tranDateTo,
                atatus = ViewBag.atatus,
                max = ViewBag.max,
                min = ViewBag.min,
                related = ViewBag.related
            };


            ObservableCollection<ReportSearchResult> gridList = new ObservableCollection<ReportSearchResult>();

            ReportServiceClient reportWebserviceClient =
                      new ReportServiceClient();
            AutoMapper.Mapper.CreateMap<ReportCriteria, ReportCriteriaDTO>();
            ReportCriteriaDTO reportCriteriaDTO = Mapper.Map<ReportCriteria, ReportCriteriaDTO>(crit);
            ExcelWSService.ExcelWSClient excelWebServicesClient = new ExcelWSService.ExcelWSClient();

            if (crit.financialInstrument == "6")
            {


                //  GetReportDepositAtFinancial

                ReportDepositAtFinancialDTO[] fixIncomeList = reportWebserviceClient.GetReportDepositAtFinancial(reportCriteriaDTO);
                if (mode == "Export")
                {

                    valueClass header = new valueClass();
                    List<valueClass> details = new List<valueClass>();
                    foreach (ReportDepositAtFinancialDTO deposit in fixIncomeList)
                    {
                        valueClass row = new valueClass()
                        {
                            string3 = convertData(deposit.DEPOSIT_COMPANY_NAME),		//Company Name 
                            string4 = convertData(deposit.MATURITY_STATUS),		//Maturity Status
                            string5 = convertData(deposit.ASSET_CLASS_ID),	//	Asset Class
                            string6 = convertData(deposit.ACCOUNT_VOUCHER_NO),	//	A/C No. / Voucher No.
                            string7 = convertData(deposit.TERM),	//	Term
                            string8 = convertData(deposit.FINANCIAL_INSTRUMENT_TYPE_ID),	//	Fianancial Instrument Type
                            string9 = convertData(deposit.BANK_NAME),	//	Bank Name
                            string10 = convertData(deposit.BRANCH_NAME),	//	Branch
                            string11 = convertData(deposit.BANK_CODE),	//	Bank Code
                            string12 = convertData(deposit.SYMBOL),	//	Symbol
                            string13 = convertData(deposit.MATURITY_DATE.ToString("dd/MM/yyyy")),	//	Maturity Date
                            string14 = convertData(deposit.INTEREST_PAYMENT_DATE.ToString("dd/MM/yyyy")),	//	Interest Payment Date
                            string15 = convertData(deposit.INTEREST_RATE.ToString("#,##0.00")),	//	Interest Rate
                            string16 = convertData(deposit.GUARANTOR),	//	Guarantor
                            string17 = convertData(deposit.LIQUIDITY_TIER_I_PERCENT.ToString("#,##0.00")),	//	Liquidity Tier I
                            string18 = convertData(deposit.LIQUIDITY_TIER_II_PERCENT.ToString("#,##0.00")),	//	Liquidity Tier II
                            string19 = convertData(deposit.LIQUIDITY_LOW_LIQUIDITY_PERCENT.ToString("#,##0.00")),	//	Liquidity Low Liquidity
                            string20 = convertData(deposit.ISSUE_RATING),	//	Issue Rating
                            string21 = convertData(deposit.ISSUE_CREDIT_AGENCY),	//	Credit Agency (Issue)
                            string22 = convertData(deposit.ISSUE_UPDATE_DATE.ToString("dd/MM/yyyy")),	//	Issue Rating Update Date
                            string43 = convertData(deposit.ISSUE_CREDIT_AGENCY_COUNTRY),	//	ISSUE_CREDIT_AGENCY_COUNTRY
                            string23 = convertData(deposit.ISSUER_RATING),	//	Issuer Rating
                            string24 = convertData(deposit.ISSUER_CREDIT_AGENCY),	//	Credit Agency (Issuer)
                            string25 = convertData(deposit.ISSUER_UPDATE_DATE.ToString("dd/MM/yyyy")),	//	Issuer Rating Update Date
                            string44 = convertData(deposit.ISSUER_CREDIT_AGENCY_COUNTRY),	//	ISSUER_CREDIT_AGENCY_COUNTRY
                            string26 = convertData(deposit.GUARANTOR_RATING),	//	Guarantor Rating
                            string27 = convertData(deposit.GUARANTOR_CREDIT_AGENCY),	//	Credit Agency (Guarantor)
                            string45 = convertData(deposit.GUARANTOR_UPDATE_DATE.ToString("dd/MM/yyyy")),	//	GUARANTOR_UPDATE_DATE
                            string46 = convertData(deposit.GUARANTOR_CREDIT_AGENCY_COUNTRY),	//	GUARANTOR_CREDIT_AGENCY_COUNTRY
                            string28 = convertData(deposit.INVOLVED_PARTY_TYPE_NAME),	//	Involved Party Type Name
                            string29 = convertData(deposit.INVOLVED_PARTY_TYPE_CODE),	//	Involved Party Type No.
                            string30 = convertData(deposit.INVOLVED_PARTY_TYPE_REFERENCE),	//	รหัสอ้างอิง คปภ. (A-E)
                            string31 = convertData(deposit.REMAIN_UNIT.ToString("#,##0.00")),	//	Remain Unit
                            string32 = convertData(deposit.TRANSACTION_TYPE),	//	ประเภทธุรกรรม
                            string33 = convertData(deposit.REF_NO),	//	Ref. No.
                            string34 = convertData(deposit.TYPEOFPAYMENT_ID),	//	 Type of Payment  
                            string35 = convertData(deposit.SETTLEMENT_DATE.ToString("dd/MM/yyyy")),	//	Settlement Date 
                            string36 = convertData(deposit.AMOUNT.ToString("#,##0.00")),	//	Amount 
                            string37 = convertData(deposit.OBLIGATION_NO_ID),	//	ภาระผูกพัน
                            string38 = convertData(deposit.GUARANTEE_TYPE),	//	ประเภทหลักประกัน
                            string39 = convertData(deposit.OBLIGATION_NO_ID),	//	สินทรัพย์จัดสรรตามมาตรา
                            string40 = convertData(deposit.AMOUNT.ToString("#,##0.00")),	//	มูลค่า
                            string41 = convertData(deposit.GUARANTEE_START_DATE.ToString("dd/MM/yyyy")),	//	วันที่เริ่มต้น
                            string42 = convertData(deposit.GUARANTEE_END_DATE.ToString("dd/MM/yyyy")),	//	วันที่สิ้นสุด

                        };

                        details.Add(row);
                    }
                    string path = excelWebServicesClient.export1("Fix Deposit", header, details.ToArray());
                    String link = ConfigurationManager.AppSettings["ExcelServiceOutputUrl"] + path;
                    return Redirect(link);
                }
                else
                {
                    //SEARCH
                    int ROW = 1;
                    GenDepositAtFinancialGrid(gridList, fixIncomeList,ref ROW);




                }
            }//END Fixed Income Securities

            else if (crit.financialInstrument == "5")
            {
                //LOAN



                ReportLoanDTO[] loanList = reportWebserviceClient.GetReportLoan(reportCriteriaDTO);
                if (mode == "Export")
                {
                    // ExcelWSService.ExcelWSClient excelClient = new ExcelWSService.ExcelWSClient();
                    valueClass header = new valueClass();
                    List<valueClass> details = new List<valueClass>();
                    foreach (ReportLoanDTO loan in loanList)
                    {
                        valueClass row = new valueClass()
                        {
                            string1 = loan.COMPANY_NAME,
                            string2 = loan.MATURITY_STATUS,
                            string3 = loan.LOAN_TYPE_NAME,
                            string4 = loan.CONTRACT_NUMBER,
                            string5 = loan.LOAN_OBJECTIVE_ID,	//	วัตถุประสงค์:
                            string6 = loan.BORROWER_NAME,	//	ชื่อผู้กู้
                            string7 = loan.BORROWER_OCCUPATION_NAME,	//	อาชีพผู้กู้
                            string8 = loan.BORROWER_ID_CARD_NO,	//	เลขที่บัตรประชาชนผู้กู้
                            string9 = loan.GUARANTOR_NAME,	//	ชื่อผู้ค้ำประกัน
                            string10 = loan.GUARANTOR_OCUUPATION_NAME,	//	อาชีพผู้ค้ำประกัน
                            string11 = loan.GUARANTOR_ID_CARD_NO,	//	เลขที่บัตรประชาชนผู้ค้ำประกัน
                            string12 = loan.GUARANTEE_TYPE_ID,	//	ประเภทหลักประกัน
                            string13 = loan.MORTGAGOR_NAME_1,	//	ชื่อผู้จำนอง (1)
                            string14 = loan.MORTGAGOR_NAME_2,	//	ชื่อผู้จำนอง (2)
                            string15 = loan.MORTGAGOR_NAME_3,	//	ชื่อผู้จำนอง (3)
                            string16 = loan.ASSESSMENT_MORTGATE_ID,	//	รายละเอียดทรัพย์สินที่ทำจำนอง
                            string17 = loan.TITLE_DEED_MAPSHEET_NO,	//	ตำแหน่งที่ดิน-ระวาง
                            string18 = loan.TITLE_DEED_PARCEL_NO,	//	ตำแหน่งที่ดิน-เลขที่ดิน
                            string19 = loan.TITLE_DEED_DEALING_FILE_NO,	//	ตำแหน่งที่ดิน-หน้าสำรวจ
                            string20 = loan.TITLE_DEED_NO,	//	โฉนดที่ดิน-เลขที่
                            string21 = loan.TITLE_DEED_VOLUMN,	//	โฉนดที่ดิน-เล่ม
                            string22 = loan.TITLE_DEED_PAGE,	//	โฉนดที่ดิน-หน้า
                            string23 = loan.TITLE_DEED_PROVINCE_NAME,	//	โฉนดที่ดิน-จังหวัด
                            string24 = loan.TITLE_DEED_DISTRICT_NAME,	//	โฉนดที่ดิน-อำเภอ
                            string25 = loan.TITLE_DEED_SUB_DISTRICT_NAME,	//	โฉนดที่ดิน-ตำบล
                            string26 = loan.TITLE_DEED_TOTAL_AREA,	//	โฉนดที่ดิน-เนื้อที่ (ไร่-งาน-ตร.วา)
                            string27 = loan.APARTMENT_NO,	//	ที่ตั้งห้องชุด-ห้องชุดเลขที่
                            string28 = loan.APARTMENT_FLOOR,	//	ที่ตั้งห้องชุด-ชั้นที่
                            string29 = loan.APARTMENT_BUILDING_NO,	//	ที่ตั้งห้องชุด-อาคารเลขที่
                            string30 = loan.APARTMENT_BUILDING_NAME,	//	ที่ตั้งห้องชุด-ชื่ออาคารชุด
                            string31 = loan.REGISTER_BUILDING_NO,	//	ที่ตั้งห้องชุด-ทะเบียนอาคารชุดเลขที่
                            string32 = loan.MORTGAGE_DATE.ToString("dd/MM/yyyy"),	//	วันที่จำนอง
                            string33 = loan.CONTRACT_START_DATE.ToString("dd/MM/yyyy"),	//	ระยะเวลาเริ่มต้น
                            string34 = loan.CONTRACT_END_DATE.ToString("dd/MM/yyyy"),	//	ระยะเวลาสิ้นสุด
                            string35 = loan.ASSESSMENT_DATE.ToString("dd/MM/yyyy"),	//	วันที่ประเมินราคาทรัพย์สินที่จำนอง
                            string36 = loan.ASSESSMENT_COST.ToString("#,##0.00"),	//	ราคาประเมิน
                            string37 = loan.ASSET_VALUE.ToString("#,##0.00"),	//	มูลค่าทรัพย์สิน/วงเงินค้ำประกัน
                            string38 = loan.CONTRACT_AMOUNT.ToString("#,##0.00"),	//	จำนวนเงินตามสัญญา 
                            string39 = loan.LIQUIDITY_TIER_I_PERCENT.ToString("#,##0.00"),	//	%Liquidity(Tier I)
                            string40 = loan.LIQUIDITY_TIER_II_PERCENT.ToString("#,##0.00"),	//	%Liquidity(Tier II)
                            string41 = loan.LIQUIDITY_LOW_LIQUIDITY_PERCENT.ToString("#,##0.00"),	//	%Liquidity(Low Liquidity)
                            string42 = loan.INVOLVED_PARTY_TYPE_NAME,	//	Involved Party Type
                            string43 = loan.INVOLVED_PARTY_TYPE_CODE,	//	Involved Party Type No
                            string44 = loan.INSURANCE_NO,	//	หมายเลข กธ.
                            string45 = loan.PROTECTION_START_DATE.ToString("dd/MM/yyyy"),	//	วันเริ่มคุ้มครอง
                            string46 = loan.PROTECTION_END_DATE.ToString("dd/MM/yyyy"),	//	วันสิ้นสุดความคุ้มครอง
                            string47 = loan.HEADER_CREATE_DATE.ToString("dd/MM/yyyy"),	//	HEADER CREATE DATE
                            string48 = loan.HEADER_CREATE_BY,	//	HEADER CREATE BY
                            string49 = loan.HEADER_MODIFY_DATE.ToString("dd/MM/yyyy"),	//	HEADER MODIFY DATE
                            string50 = loan.HEADER_MODIFY_BY,	//	HEADER MODIFY BY
                            string51 = loan.INTEREST_PERIOD.ToString("#,##0.00"),	//	Period
                            string52 = loan.MLR_DATE.ToString("dd/MM/yyyy"),	//	MLR Rate Date
                            string53 = loan.MLR_RATE.ToString("#,##0.00"),	//	MLR Rate
                            string54 = loan.MLR_MINUS.ToString("#,##0.00"),	//	MLR (-)
                            string55 = loan.INTEREST_RATE.ToString("#,##0.00"),	//	INTEREST RATE
                            string56 = loan.UPDATE_INFO,	//	Update Info
                            string57 = loan.INSTALLMENT.ToString("#,##0.00"),	//	Installment
                            string58 = loan.INTEREST_CREATE_DATE.ToString("dd/MM/yyyy"),	//	INTEREST CREATE DATE
                            string59 = loan.INTEREST_CREATE_BY,	//	INTEREST CREATE BY
                            string60 = loan.INTEREST_MODIFY_DATE.ToString("dd/MM/yyyy"),	//	INTEREST MODIFY DATE
                            string61 = loan.INTEREST_MODIFY_BY,	//	INTEREST MODIFY BY
                            string62 = loan.NEW_INSTALLMENT.ToString("#,##0.00"),	//	New Installment Rate
                            string63 = loan.EXTRAINSTALLMENT_DATE.ToString("dd/MM/yyyy"),	//	Extra Installment Date
                            string64 = loan.EXTRAINSTALLMENT_RATE.ToString("#,##0.00"),	//	Extra Installment Rate
                            string65 = loan.CLOSE_ACCOUNT_DATE.ToString("dd/MM/yyyy"),	//	Close Account Date
                            string66 = loan.CLOSE_ACCOUNT_INTEREST.ToString("#,##0.00"),	//	Close Account Interest
                            string67 = loan.CLOSE_ACCOUNT_PRINCIPLE.ToString("#,##0.00"),	//	Close Account Principle
                            string68 = loan.CLOSE_ACCOUNT_TOTAL.ToString("#,##0.00"),	//	Close Account Total
                            string69 = loan.EXTRA_INSTALLMENT_CREATE_DATE.ToString("dd/MM/yyyy"),	//	EXTRA INSTALLMENT CREATE DATE
                            string70 = loan.EXTRA_INSTALLMENT_CREATE_BY,	//	EXTRA INSTALLMENT CREATE BY
                            string71 = loan.EXTRA_INSTALLMENT_MODIFY_DATE.ToString("dd/MM/yyyy"),	//	EXTRA INSTALLMENT MODIFY DATE
                            string72 = loan.EXTRA_INSTALLMENT_MODIFY_BY,	//	EXTRA INSTALLMENT MODIFY BY


                        };

                        details.Add(row);
                    }
                    string path = excelWebServicesClient.export1("LOAN", header, details.ToArray());
                    String link = ConfigurationManager.AppSettings["ExcelServiceOutputUrl"] + path;
                    return Redirect(link);
                }
                else
                {
                    //SEARCH
                    int ROW = 1;
                    GenLoanGrid(gridList, loanList,ref ROW);




  
                }
            }//END LOAN
            else if (crit.financialInstrument == "2")
            {
                //EQUITY



                ReportEquityDTO[] equityList = reportWebserviceClient.GetReportEquity(reportCriteriaDTO);
                if (mode == "Export")
                {

                    valueClass header = new valueClass();
                    List<valueClass> details = new List<valueClass>();
                    foreach (ReportEquityDTO obj in equityList)
                    {
                        valueClass row = new valueClass()
                        {
                            string1 = obj.EQUITY_COMPANY_NAME,	//	Company Name
                            string2 = obj.MATURITY_STATUS,	//	Maturity Status
                            string3 = obj.FULL_NAME_EN,	//	Full Name (EN)
                            string4 = obj.FULL_NAME_TH,	//	Full Name (TH)
                            string5 = obj.EQUITY_TYPE_NAME,	//	Equity Type
                            string6 = obj.EQUITY_SECTOR_GROUP,	//	Sector Group
                            string7 = obj.EQUITY_SECTOR,	//	Sector
                            string8 = obj.SYMBOL,	//	Symbol
                            string9 = obj.LISTED_STATUS,	//	Listed Status
                            string10 = obj.BROKER,	//	Broker
                            string11 = obj.CAPITAL_REGISTERED.ToString("#,##0.00"),	//	Capital Registered
                            string12 = obj.CAPITAL_PAID.ToString(),	//	Capital Paid
                            string13 = obj.INVOLVED_PARTY_TYPE_NAME,	//	Involved Party Type Name
                            string14 = obj.INVOLVED_PARTY_TYPE_CODE,	//	Involved Party Type No.
                            string15 = obj.INVOLVED_PARTY_TYPE_REFERENCE,	//	รหัสอ้างอิง คปภ. (A-E)
                            string16 = obj.REMAIN_UNIT.ToString(),	//	Remain Unit
                            string17 = obj.BID_PRICE_DATE.ToString("dd/MM/yyyy"),	//	Bid Price Date
                            string18 = obj.BID_PRICE_PER_UNIT.ToString("#,##0.00"),	//	Bid Price per Unit
                            string19 = obj.BID_AMOUNT.ToString("#,##0.00"),	//	Bid AMOUNT
                            string20 = obj.BV_PRICE_DATE.ToString("dd/MM/yyyy"),	//	BV Price Date
                            string21 = obj.BV_PRICE_PER_UNIT.ToString("#,##0.00"),	//	BV Price per Unit
                            string22 = obj.BV_AMOUNT.ToString("#,##0.00"),	//	BV AMOUNT
                            string23 = obj.FV_PRICE_DATE.ToString("dd/MM/yyyy"),	//	FV Price Date
                            string24 = obj.FV_PRICE_PER_UNIT.ToString("#,##0.00"),	//	FV Price per Unit
                            string25 = obj.FV_AMOUNT.ToString("#,##0.00"),	//	FV AMOUNT
                            string26 = obj.CLOSE_PRICE_DATE.ToString("dd/MM/yyyy"),	//	Close Price Date
                            string27 = obj.CLOSE_PRICE_PER_UNIT.ToString("#,##0.00"),	//	Close Price per Unit
                            string28 = obj.CLOSE_AMOUNT.ToString("#,##0.00"),	//	Close AMOUNT
                            string29 = obj.LIQUIDITY_TIER_I_PERCENT.ToString("#,##0.00"),	//	%Liquidity(Tier I)
                            string30 = obj.LIQUIDITY_TIER_II_PERCENT.ToString("#,##0.00"),	//	%Liquidity(Tier II)
                            string31 = obj.LIQUIDITY_LOW_LIQUIDITY_PERCENT.ToString("#,##0.00"),	//	%Liquidity(Low Liquidity)
                            string32 = obj.RELATED_ID,	//	Relate
                            string33 = obj.REMARK_OIC,	//	Remark (OIC)
                            string34 = obj.HEADER_CREATE_DATE.ToString("dd/MM/yyyy"),	//	CREATE DATE
                            string35 = obj.HEADER_CREATE_BY,	//	CREATE BY
                            string36 = obj.HEADER_MODIFY_DATE.ToString("dd/MM/yyyy"),	//	MODIFY DATE
                            string37 = obj.HEADER_MODIFY_BY,	//	MODIFY BY
                            string38 = obj.TRANSACTION_TYPE,	//	Transaction Type
                            string39 = obj.REF_NO,	//	Ref. No.
                            string40 = obj.TYPEOFPAYMENT_ID,	//	Type of Payment
                            string41 = obj.TRADE_DATE.ToString("dd/MM/yyyy"),	//	Trade Date
                            string42 = obj.SETTLEMENT_DATE.ToString("dd/MM/yyyy"),	//	Settlement Date
                            string43 = obj.UNIT.ToString(),	//	Unit
                            string44 = obj.PAR_UNIT.ToString("#,##0.00"),	//	Par / Unit
                            string45 = obj.PAR_AMOUNT.ToString("#,##0.00"),	//	Par Amount
                            string46 = obj.PRICE_UNIT.ToString("#,##0.00"),	//	Price / Unit
                            string47 = obj.GROSS_AMOUNT.ToString("#,##0.00"),	//	Gross Amount
                            string48 = obj.COM_RATE.ToString("#,##0.00"),	//	COM. Rate
                            string49 = obj.COM_AMOUNT.ToString("#,##0.00"),	//	COM AMOUNT
                            string50 = obj.VAT_RATE.ToString("#,##0.00"),	//	VAT Rate
                            string51 = obj.VAT_AMOUNT.ToString("#,##0.00"),	//	VAT AMOUNT
                            string52 = obj.PURCHASE_VALUE_NET.ToString("#,##0.00"),	//	Purchase Value (Net)
                            string53 = obj.WH_TAX_RATE.ToString("#,##0.00"),	//	W/H TAX Rate
                            string54 = obj.WH_TAX_AMOUNT.ToString("#,##0.00"),	//	W/H TAX AMOUNT
                            string55 = obj.NET_SETTLE.ToString("#,##0.00"),	//	Net Settle AMT. incl W/T
                            string56 = obj.PHYSICAL_ID,	//	Physical
                            string57 = obj.KEEP_AT_ID,	//	Keep at
                            string58 = obj.OBLIGATION_ID,	//	ภาระผูกพัน
                            string59 = obj.OBLIGATION_NO_ID,	//	ภาระผูกพันตามมาตรา
                            string60 = obj.GUARANTEE_START_DATE.ToString("dd/MM/yyyy"),	//	Start Date
                            string61 = obj.GUARANTEE_END_DATE.ToString("dd/MM/yyyy"),	//	End Date
                            string62 = obj.TRANS_CREATE_DATE.ToString("dd/MM/yyyy"),	//	TRANS. CREATE DATE
                            string63 = obj.TRANS_MODIFY_BY,	//	TRANS. CREATE BY
                            string64 = obj.TRANS_MODIFY_DATE.ToString("dd/MM/yyyy"),	//	TRANS. MODIFY DATE
                            string65 = obj.TRANS_MODIFY_BY,	//	TRANS. MODIFY BY
                            string66 = obj.TYPEOFPAYMENT_ID,	//	Type
                            string67 = obj.EX_DATE.ToString("dd/MM/yyyy"),	//	Ex Date 
                            string68 = obj.BCD_DATE.ToString("dd/MM/yyyy"),	//	Book Closing Date (BCD)
                            string69 = obj.DIV_UNIT.ToString("#,##0.00"),	//	DIV./UNIT
                            string70 = obj.DIV_AMOUNT.ToString("#,##0.00"),	//	DIV. (AMOUNT)
                            string71 = obj.DIV_STOCK.ToString("#,##0.00"),	//	DIV. - Stock
                            string72 = obj.FRACTION_UNIT.ToString("#,##0.00"),	//	UNIT (เศษหุ้น)
                            string73 = obj.FRACTION_DIV_UNIT.ToString("#,##0.00"),	//	DIV./UNIT (เศษหุ้น)
                            string74 = obj.UNIT.ToString("#,##0.00"),	//	Amortize / Unit
                            string75 = obj.PRICE_UNIT.ToString("#,##0.00"),	//	ราคาต่อหุ้น:
                            string76 = obj.RIGHT_OLD_NEW.ToString("#,##0.00"),	//	Right Old : New
                            string77 = obj.PAYMENT_DATE.ToString("dd/MM/yyyy"),	//	Payment Date
                            string78 = obj.TRANNSAFER_DATE.ToString("dd/MM/yyyy"),	//	วันที่แปลงหุ้น
                            string79 = obj.TRANNSAFER_PRICE.ToString("#,##0.00"),	//	ราคาแปลงหุ้น 
                            string80 = obj.PRIVILEGE_CREATE_DATE.ToString("dd/MM/yyyy"),	//	PRIVILEGE CREATE DATE
                            string81 = obj.PRIVILEGE_CREATE_BY,	//	PRIVILEGE CREATE BY
                            string82 = obj.PRIVILEGE_MODIFY_DATE.ToString("dd/MM/yyyy"),	//	PRIVILEGE MODIFY DATE
                            string83 = obj.PRIVILEGE_MODIFY_BY,	//	PRIVILEGE MODIFY BY

                        };

                        details.Add(row);
                    }
                    string path = excelWebServicesClient.export1("Equity Securities", header, details.ToArray());//Equity Securities report template
                    String link = ConfigurationManager.AppSettings["ExcelServiceOutputUrl"] + path;
                    return Redirect(link);
                }
                else
                {
                    //SEARCH
                    int ROW = 1;
                    GenEquityGrid(gridList, equityList,ref ROW);



                }

            }//END EQUITY
            else
                if (crit.financialInstrument == "1")
                {
                    //Fixed Income



                    ReportFixedIncomeDTO[] fixIncomeList = reportWebserviceClient.GetReportFixedIncome(reportCriteriaDTO);
                    if (mode == "Export")
                    {
                        ExcelWSService.ExcelWSClient excelClient = new ExcelWSService.ExcelWSClient();
                        valueClass header = new valueClass();
                        List<valueClass> details = new List<valueClass>();
                        foreach (ReportFixedIncomeDTO obj in fixIncomeList)
                        {
                            valueClass row = new valueClass()
                            {
                                string1 = obj.COMPANY_NAME,	//	Company Name
                                string2 = obj.MATURITY_STATUS,	//	Maturity Status
                                string3 = obj.FIXED_INCOME_FULLNAME_EN,	//	Full Name
                                string4 = obj.ISSUER_NAME,	//	Issuer
                                string5 = obj.ISSUER_TYPE_NAME,	//	 Issuer Type 
                                string6 = obj.SYMBOL,	//	Symbol
                                string7 = obj.GUARANTOR_TYPE_NAME,	//	 Guarantor Type 
                                string8 = obj.GUARANTOR_NAME,	//	Guarantor
                                string9 = obj.GUARANTOR_OTHER_NAME,	//	Guarantor Other
                                string10 = obj.ISIN_CODE,	//	ISIN Code 
                                string11 = obj.BOND_TYPE_NAME,	//	Bond Type
                                string12 = obj.LISTED_STATUS,	//	Listed Status
                                string13 = obj.NUMBER_TIME,	//	ครั้งที่ออก
                                string14 = obj.INITIAL_PAR_UNIT.ToString("#,##0.00"),	//	Initial Par / Unit
                                string15 = obj.CURRENT_PAR_UNIT.ToString("#,##0.00"),	//	Current Par / Unit
                                string16 = obj.COUPON.ToString("#,##0.00"),	//	Coupon
                                string17 = obj.ISSUE_DATE.ToString("dd/MM/yyyy"),	//	Issue Date
                                string18 = obj.COUPON_PAYMENT_DATE.ToString("dd/MM/yyyy"),	//	 Coupon payment date
                                string19 = obj.MATURITY_DATE.ToString("dd/MM/yyyy"),	//	Maturity Date 
                                string20 = obj.CALCULATION_METHOD,	//	Calculation Method
                                string21 = obj.ISSUER_TERM.ToString("#,##0.00"),	//	 Issue Term 
                                string22 = obj.PAYMENT_FREQUENCY.ToString(),	//	Payment Frequency
                                string23 = obj.ISSUE_RATING,	//	Issue Rating
                                string24 = obj.ISSUE_CREDIT_AGENCY,	//	Credit Agency (Issue)
                                string25 = obj.ISSUE_UPDATE_DATE.ToString("dd/MM/yyyy"),	//	Issue Rating Update Date
                                string81 = obj.ISSUE_CREDIT_AGENCY_COUNTRY,	//	ISSUE_CREDIT_AGENCY_COUNTRY
                                string26 = obj.ISSUER_RATING,	//	Issuer Rating
                                string27 = obj.ISSUER_CREDIT_AGENCY,	//	Credit Agency (Issuer)
                                string28 = obj.ISSUER_UPDATE_DATE.ToString("dd/MM/yyyy"),	//	Issuer Rating Update Date
                                string82 = obj.ISSUER_CREDIT_AGENCY_COUNTRY,	//	ISSUE_CREDIT_AGENCY_COUNTRY
                                string29 = obj.GUARANTOR_RATING,	//	Guarantor Rating
                                string30 = obj.GUARANTOR_CREDIT_AGENCY,	//	Credit Agency (Guarantor)
                                string31 = obj.GUARANTOR_UPDATE_DATE.ToString("dd/MM/yyyy"),	//	Guarantor Rating Update Date
                                string83 = obj.GUARANTOR_CREDIT_AGENCY_COUNTRY,	//	ISSUE_CREDIT_AGENCY_COUNTRY
                                string32 = obj.RISK_LEVEL,	//	Risk Level
                                string33 = obj.LIQUIDITY_TIER_I_PERCENT.ToString("#,##0.00"),	//	Liquidity Tier I
                                string34 = obj.LIQUIDITY_TIER_II_PERCENT.ToString("#,##0.00"),	//	Liquidity Tier II
                                string35 = obj.LIQUIDITY_LOW_LIQUIDITY_PERCENT.ToString("#,##0.00"),	//	Liquidity Low Liquidity
                                string36 = obj.INVOLVED_PARTY_TYPE_NAME,	//	Involved Party Type Name
                                string37 = obj.INVOLVED_PARTY_TYPE_CODE,	//	Involved Party Type No.
                                string38 = obj.INVOLVED_PARTY_TYPE_REFERENCE,	//	รหัสอ้างอิง คปภ. (A-E)
                                string39 = obj.TRANSACTION_TYPE,	//	ประเภทธุรกรรม
                                string40 = obj.REF_NO,	//	Ref. No.
                                string41 = obj.TYPEOFPAYMENT_NAME,	//	Type of Payment 
                                string42 = obj.TIME2MATURE.ToString("#,##0.00"),	//	Time to Maturity Date
                                string43 = obj.TRADE_DATE.ToString("dd/MM/yyyy"),	//	Trade Date 
                                string44 = obj.SETTLEMENT_DATE.ToString("dd/MM/yyyy"),	//	Settlement Date 
                                string45 = obj.UNIT.ToString(),	//	Unit
                                string46 = obj.TOTALSIZE.ToString(),	//	Total Size
                                string47 = obj.PAR.ToString("#,##0.00"),	//	Par
                                string48 = obj.PAR_VALUE.ToString("#,##0.00"),	//	Par Value
                                string49 = obj.YIELD.ToString("#,##0.00"),	//	Yield 
                                string50 = obj.CLEAN_PRICE.ToString("#,##0.00"),	//	Clean Price
                                string51 = obj.AI.ToString("#,##0.00"),	//	AI
                                string52 = obj.GROSS_PRICE.ToString("#,##0.00"),	//	Gross Price
                                string53 = obj.DISCOUNT_PREMIUM.ToString("#,##0.00"),	//	Discount / Premium
                                string54 = obj.PHYSICAL,	//	Physical
                                string55 = obj.KEEP_AT,	//	Keep at
                                string56 = obj.COUNTERPARTY_NAME,	//	Counterparty
                                string57 = obj.PURCHASE_VALUE_TH.ToString("#,##0.00"),	//	Purchase Value (Local THB)
                                string58 = obj.CURRENCY,	//	Currency
                                string59 = obj.EXCH_RATE.ToString("#,##0.00"),	//	Exch. Rate
                                string60 = obj.PURCHASE_VALUE_FOREIGN.ToString("#,##0.00"),	//	Purchase Value (Foreign)
                                string61 = obj.RELATED,	//	Related / Non Related
                                string62 = obj.INDEX_RATIO,	//	Index Ratio
                                string63 = obj.REMARK_OIC,	//	Remark (OIC)
                                string64 = obj.REMAIN_UNIT.ToString(),	//	Remain Unit
                                string65 = obj.TRANSACTION_TYPE_transaction,	//	ประเภทธุรกรรม
                                string66 = obj.Trade_Date_transaction.ToString("dd/MM/yyyy"),	//	Trade Date
                                string67 = obj.Settlement_Date_transaction.ToString("dd/MM/yyyy"),	//	Settlement Date 
                                string68 = obj.UNIT_transaction.ToString("#,##0.00"),	//	Unit 
                                string69 = obj.YIELD_transaction.ToString("#,##0.00"),	//	Yield 
                                string70 = obj.COUNTERPARTY_NAME_transaction,	//	Counter party 
                                string71 = obj.CLEANPRICE_transaction.ToString("#,##0.00"),	//	Clean Price 
                                string72 = obj.TYPEOFPAYMENT_NAME_transaction,	//	Type of Payment 
                                string73 = obj.AI_transaction.ToString("#,##0.00"),	//	AI
                                string74 = obj.REF_NO_transaction,	//	Ref. No.
                                string75 = obj.GROSS_PRICE_transaction.ToString("#,##0.00"),	//	Gross Price
                                string76 = obj.OBLIGATION_transaction,	//	ภาระผูกพัน
                                string77 = obj.GUARANTEE_TYPE_transaction,	//	ประเภทหลักประกัน
                                string78 = obj.OBLIGATION_NO_transaction,	//	ภาระผูกพันตามมาตรา
                                string79 = obj.GUARANTEE_STARTDATE_transaction.ToString("dd/MM/yyyy"),	//	Start Date 
                                string80 = obj.GUARANTEE_ENDDATE_transaction.ToString("dd/MM/yyyy"),	//	End Date

                            };

                            details.Add(row);
                        }
                        string path = excelWebServicesClient.export1("Fixed Income Securities", header, details.ToArray());
                        String link = ConfigurationManager.AppSettings["ExcelServiceOutputUrl"] + path;
                        return Redirect(link);
                    }
                    else
                    {
                        //SEARCH
                        int ROW = 1;
                        GenFixedIncomeGrid(gridList, fixIncomeList,ref ROW);



                    }
                }//END FixedIncome

                else if (crit.financialInstrument == "3")
                {
                    //unit trust Gift



                    ReportUnitTrustsDTO[] unitTrustList = reportWebserviceClient.GetReportUnitTrusts(reportCriteriaDTO);
                    if (mode == "Export")
                    {
                        ExcelWSService.ExcelWSClient excelClient = new ExcelWSService.ExcelWSClient();
                        valueClass header = new valueClass();
                        List<valueClass> details = new List<valueClass>();
                        foreach (ReportUnitTrustsDTO obj in unitTrustList)
                        {
                            valueClass row = new valueClass()
                            {
                                string1 = obj.UNIT_TRUST_COMPANY_NAME,	//	Company Name 
                                string2 = obj.MATURITY_STATUS,	//	Maturity Status
                                string3 = obj.UNIT_TRUST_TYPE_NAME,	//	Type 
                                string4 = obj.UNIT_TRUST_TYPE_GROUP,	//	Group of Type
                                string5 = obj.FUND_NAME,	//	 Fund Name 
                                string6 = obj.LISTED_STATUS,	//	Listed Status
                                string7 = obj.ASSET_MGMT_NAME,	//	 Asset Management  
                                string8 = obj.SYMBOL,	//	Symbol 
                                string9 = obj.TOTAL_SIZE.ToString(),	//	Total size
                                string10 = obj.MATURITY_DATE.ToString("dd/MM/yyyy"),	//	Maturity Date
                                string11 = obj.BID_PRICE.ToString("#,##0.00"),	//	Bid Price / NAV
                                string12 = obj.INITIAL_PAR.ToString("#,##0.00"),	//	Initial Par
                                string13 = obj.BID_PRICE_DATE.ToString("dd/MM/yyyy"),	//	Bid Price as of / NAV as of
                                string14 = obj.PAR.ToString("#,##0.00"),	//	Par
                                string15 = obj.PAR_DATE.ToString("dd/MM/yyyy"),	//	Par As Date
                                string16 = obj.LIQUIDITY_TIER_I_PERCENT.ToString("#,##0.00"),	//	Liquidity Tier I
                                string17 = obj.LIQUIDITY_TIER_II_PERCENT.ToString("#,##0.00"),	//	Liquidity Tier II
                                string18 = obj.LIQUIDITY_LOW_LIQUIDITY_PERCENT.ToString("#,##0.00"),	//	Liquidity Low Liquidity
                                string19 = obj.INVOLVED_PARTY_TYPE_NAME,	//	Involved Party Type Name
                                string20 = "",	//	Involved Party Type No.
                                string21 = "",	//	 รหัสอ้างอิง คปภ. (A-E)  
                                string22 = obj.RELATED,	//	Relate
                                string23 = obj.REMARK_OIC,	//	Remark (OIC)
                                string24 = obj.TRANSACTION_TYPE,	//	Transaction Type
                                string25 = obj.REF_NO,	//	Ref. No.
                                string26 = obj.TYPEOFPAYMENT_NAME,	//	Type of Payment 
                                string27 = obj.TRADE_DATE.ToString("dd/MM/yyyy"),	//	Trade Date
                                string28 = obj.SETTLEMENT_DATE.ToString("dd/MM/yyyy"),	//	Settlement Date 
                                string29 = obj.UNIT.ToString(),	//	Unit 
                                string30 = obj.PRICE_UNIT.ToString("#,##0.00"),	//	Price / Unit
                                string31 = obj.GROSS_AMOUNT.ToString("#,##0.00"),	//	Gross Amount
                                string32 = obj.COM_RATE.ToString("#,##0.00"),	//	COM 
                                string33 = obj.COM_AMOUNT.ToString("#,##0.00"),	//	COM AMOUNT
                                string34 = obj.VAT_RATE.ToString("#,##0.00"),	//	VAT Rate
                                string35 = obj.VAT_AMOUNT.ToString("#,##0.00"),	//	VAT AMOUNT
                                string36 = obj.PURCHASE_VALUE_NET.ToString("#,##0.00"),	//	Purchase Value (Net)
                                string37 = obj.WH_TAX_RATE.ToString("#,##0.00"),	//	W/H TAX Rate
                                string38 = obj.WH_TAX_AMOUNT.ToString("#,##0.00"),	//	W/H TAX AMOUNT 
                                string39 = obj.NET_SETTLE.ToString("#,##0.00"),	//	Net Settle AMT. incl W/T
                                string40 = obj.PHYSICAL,	//	Physical 
                                string41 = obj.KEEP_AT,	//	Keep at
                                string42 = obj.OBLIGATION,	//	ภาระผูกพัน
                                string43 = obj.OBLIGATION_NO,	//	ภาระผูกพันตามมาตรา 
                                string44 = obj.GUARANTEE_START_DATE.ToString("dd/MM/yyyy"),	//	Start Date
                                string45 = obj.GUARANTEE_END_DATE.ToString("dd/MM/yyyy"),	//	End Date
                                string46 = "",	//	จำนวนที่ถือครอง Unit 
                                string47 = "",	//	Type 
                                string48 = "",	//	Ex Date
                                string49 = "",	//	Book Closing Date (BCD)
                                string50 = "",	//	Type of Payment
                                string51 = "",	//	Payment Date
                                string52 = "",	//	DIV./UNIT
                                string53 = "",	//	DIV. (AMOUNT)
                                string54 = "",	//	Right Old / New
                                string55 = "",	//	DIV. - Stock 
                                string56 = "",	//	UNIT (เศษหุ้น)
                                string57 = "",	//	DIV./UNIT (เศษหุ้น)
                                string58 = "",	//	Amortize / Unit 
                                string59 = "",	//	ราคาต่อหุ้น
                                string60 = "",	//	วันที่แปลงหุ้น
                                string61 = ""		//	ราคาแปลงหุ้น

                            };

                            details.Add(row);
                        }
                        string path = excelWebServicesClient.export1("Unit Trust Securities", header, details.ToArray());
                        String link = ConfigurationManager.AppSettings["ExcelServiceOutputUrl"] + path;
                        return Redirect(link);
                    }
                    else
                    {
                        //SEARCH
                        int ROW = 1;
                        GenUnitTrustGrid(gridList, unitTrustList,ref ROW);



                    }
                }//END UnitTrust
                else
                {
                    ReportDepositAtFinancialDTO[] depositAtFinancialList = reportWebserviceClient.GetReportDepositAtFinancial(reportCriteriaDTO);
                    ReportLoanDTO[] loanList = reportWebserviceClient.GetReportLoan(reportCriteriaDTO);
                    ReportEquityDTO[] equityList = reportWebserviceClient.GetReportEquity(reportCriteriaDTO);
                    ReportFixedIncomeDTO[] fixIncomeList = reportWebserviceClient.GetReportFixedIncome(reportCriteriaDTO);
                    ReportUnitTrustsDTO[] unitTrustList = reportWebserviceClient.GetReportUnitTrusts(reportCriteriaDTO);
                      int ROW = 1;
                    GenDepositAtFinancialGrid(gridList, depositAtFinancialList,ref ROW);
                  
                    GenLoanGrid(gridList, loanList,ref ROW);
                    GenEquityGrid(gridList, equityList ,ref ROW);
                    GenUnitTrustGrid(gridList, unitTrustList ,ref ROW);
                    GenFixedIncomeGrid(gridList, fixIncomeList, ref ROW);
                }
           
          
            var list1=  gridList.OrderBy(t => float.Parse((t.TimeToMaturity == "N/A") ? "0" : t.TimeToMaturity)).ToList<ReportSearchResult>();
            int ii=1;
            foreach (ReportSearchResult v in list1)
            {
                v.no=ii++;
            }
            return View("Index", list1);

        }

        private string convertData(string data)
        {
            return String.IsNullOrEmpty(data) ? "" : data;
        }
        private string convertData(DateTime data)
        {
            //DateTime myDateTime =  Convert.ToDateTime("1/1/0001 12:00:00 AM");
            //int isTrue = DateTime.Compare(data,myDateTime);

            return data == null ? "" : data.ToString("dd/MM/yyyy");
        }
        private string convertData(decimal data)
        {
            return data == null ? "" : data.ToString("#,##0.00");
        }
     
        //static int ROW = 1;
        private static void GenDepositAtFinancialGrid(ObservableCollection<ReportSearchResult> gridList, ReportDepositAtFinancialDTO[] fixIncomeList,ref int ROW)
        {

            foreach (ReportDepositAtFinancialDTO deposit in fixIncomeList)
            {
                ReportSearchResult result = new ReportSearchResult()
                {

                    no = ROW++,
                    HeaderId = deposit.DEPOSIT_HEADER_ID,
                    Company = deposit.DEPOSIT_COMPANY_NAME,
                    FinancialInstrument = "Deposit Securities",
                    AssetClass = deposit.ASSET_CLASS_ID,
                    Symbol = deposit.ACCOUNT_VOUCHER_NO,
                    TransactionType = deposit.TRANSACTION_TYPE,
                    TransactionDate = deposit.SETTLEMENT_DATE.ToString("dd/MM/yyyy"),
                    Issuer = deposit.SYMBOL,
                    KeepAt = "", // not found
                    TimeToMaturity = (deposit.MATURITY_DATE_CAL == 0) ? "N/A" : deposit.MATURITY_DATE_CAL.ToString("#,##0.00"),
                    CostYieldInterestRate = "",
                    RelatedNonRelated = "",// not found
                    _page = "EditDepositHeader",
                    _folder = "Deposit"
                };
                gridList.Add(result);
            }
        }

        private static void GenLoanGrid(ObservableCollection<ReportSearchResult> gridList, ReportLoanDTO[] loanList,ref int ROW)
        {

            foreach (ReportLoanDTO loan in loanList)
            {
                ReportSearchResult result = new ReportSearchResult()
                {
                    no = ROW++,
                    HeaderId = loan.LOANS_HEADER_ID,
                    Company = loan.COMPANY_NAME,
                    FinancialInstrument = "Loans",
                    AssetClass = "",
                    Symbol = loan.CONTRACT_NUMBER,
                    TransactionType = "",
                    TransactionDate = loan.CONTRACT_START_DATE.ToString("dd/MM/yyyy"),
                    Issuer = loan.COMPANY_NAME,
                    KeepAt = "",
                    TimeToMaturity = (loan.TIME_TO_MATURITY == 0) ? "N/A" : loan.TIME_TO_MATURITY.ToString("#,##0.00"),
                    CostYieldInterestRate = loan.INTEREST_RATE.ToString("#,##0.00"),
                    RelatedNonRelated = "",

                    _page = "EditLoanHeader",
                    _folder = "Loan"
                };
                gridList.Add(result);
            }
        }

        private static void GenEquityGrid(ObservableCollection<ReportSearchResult> gridList, ReportEquityDTO[] equityList, ref int ROW)
        {
            string keepAt = "";

            

            foreach (ReportEquityDTO equity in equityList)
            {
                string transactionDate;
                string transactionType;

                if (equity.TRANSACTION_TYPE.Equals("Purchase") || equity.TRANSACTION_TYPE.Equals("Subscription") || equity.TRANSACTION_TYPE.Equals("Sale") || equity.TRANSACTION_TYPE.Equals("Guarantee"))
                {
                    transactionDate = equity.TRADE_DATE.ToString("dd/MM/yyyy");
                    keepAt = equity.KEEP_AT_ID;
                    transactionType = equity.TRANSACTION_TYPE;
                }
                else
                {
                    transactionDate = equity.PAYMENT_DATE.ToString("dd/MM/yyyy");
                    keepAt = "";
                    transactionType = "Privilege";
                }


                ReportSearchResult result = new ReportSearchResult()
                {
                    
                    no = ROW++,
                    HeaderId = equity.EQUITY_HEADER_ID,
                    Company = equity.EQUITY_COMPANY_NAME,
                    FinancialInstrument = "Equity Securities",
                    AssetClass = "",// no id
                    Symbol = equity.SYMBOL,
                    TransactionType = transactionType,
                    TransactionDate = transactionDate,
                    Issuer = equity.SYMBOL,
                    KeepAt = keepAt,
                    TimeToMaturity = "N/A", // not found
                    CostYieldInterestRate = "",
                    RelatedNonRelated = equity.RELATED_ID,

                    _page = "EditEquityHeader",
                    _folder = "Equity"
                };
                gridList.Add(result);
            }
        }

        private static void GenFixedIncomeGrid(ObservableCollection<ReportSearchResult> gridList, ReportFixedIncomeDTO[] fixIncomeList, ref int ROW)
        {

            foreach (ReportFixedIncomeDTO fixInc in fixIncomeList)
            {
                string transactionDate;
                string relatedNonRelated_;
                decimal yield;
                if (fixInc.TRANSACTION_TYPE.Equals("Purchase") || fixInc.TRANSACTION_TYPE.Equals("Subscription"))
                {
                    transactionDate = fixInc.TRADE_DATE.ToString("dd/MM/yyyy");
                    yield = fixInc.YIELD;
                    relatedNonRelated_ = fixInc.RELATED;
                }
                else
                {
                    transactionDate = fixInc.Trade_Date_transaction.ToString("dd/MM/yyyy");
                    yield = fixInc.YIELD_transaction;
                    relatedNonRelated_ = "";
                }////fixInc.MATURITY_DATE.ToString("dd/MM/yyyy"),
                    
              
               
                ReportSearchResult result = new ReportSearchResult()
                {

                    no = ROW++,
                    HeaderId = fixInc.FIXINCOMESECURITIES_HEADER_ID,
                    Company = fixInc.COMPANY_NAME,
                    FinancialInstrument = "Fixed Income Securities",
                    AssetClass = "",
                    Symbol = fixInc.SYMBOL,
                    TransactionType = fixInc.TRANSACTION_TYPE,
                    TransactionDate = transactionDate,
                    Issuer = fixInc.ISSUER_NAME,
                    KeepAt = fixInc.KEEP_AT,
                    TimeToMaturity = (fixInc.MATURITY_DATE_CAL == 0) ? "N/A" : fixInc.MATURITY_DATE_CAL.ToString("#,##0.00"),
                    CostYieldInterestRate = yield.ToString("#,##0.00"),
                    RelatedNonRelated = relatedNonRelated_,

                    _page = "EditFixedIncome",
                    _folder = "FixedIncome"
                };
                gridList.Add(result);
            }
        }

        private static void GenUnitTrustGrid(ObservableCollection<ReportSearchResult> gridList, ReportUnitTrustsDTO[] unitTrustList, ref int ROW)
        {

            foreach (ReportUnitTrustsDTO unitTrust in unitTrustList)
            {
                string transactionDate;
                string transactionType;

                if (unitTrust.TRANSACTION_TYPE
                    != null)
                {
                    if (unitTrust.TRANSACTION_TYPE.Equals("Purchase") || unitTrust.TRANSACTION_TYPE.Equals("Sale") || unitTrust.TRANSACTION_TYPE.Equals("Guarantee"))
                    {
                        transactionDate = unitTrust.TRADE_DATE.ToString("dd/MM/yyyy");
                        transactionType = unitTrust.TRANSACTION_TYPE.ToString();
                    }
                    else
                    {
                        transactionDate = unitTrust.PAYMENT_DATE.ToString("dd/MM/yyyy");
                        transactionType = "Privilege";
                    }
                }
                else
                {
                    transactionDate = unitTrust.PAYMENT_DATE.ToString("dd/MM/yyyy");
                    transactionType = "";
                }

                ReportSearchResult result = new ReportSearchResult()
                {

                    no = ROW++,
                    HeaderId = unitTrust.UNIT_TRUST_HEADER_ID,
                    Company = unitTrust.UNIT_TRUST_COMPANY_NAME,
                    FinancialInstrument = "Unit Trust Securities",
                    AssetClass = "",
                    Symbol = unitTrust.SYMBOL,
                    TransactionType = transactionType,
                    TransactionDate = unitTrust.TRADE_DATE.ToString("dd/MM/yyyy"),
                    Issuer = unitTrust.ASSET_MGMT_NAME,
                    KeepAt = unitTrust.KEEP_AT,
                    TimeToMaturity = (unitTrust.MATURITY_DATE_CAL==0)?"N/A": unitTrust.MATURITY_DATE_CAL.ToString("#,##0.00"),
                    CostYieldInterestRate = "",
                    RelatedNonRelated = unitTrust.RELATED.ToString(),

                    _page = "EditUnitTrustHeader",
                    _folder = "UnitTrust"

                    /* RelatedNonRelated unknow tated_id
                     */
                };
                gridList.Add(result);
            }
        }
    }
}
